import { createContext } from 'react';
import type { Dispatch, SetStateAction } from 'react';
import type { AnyObject, ContextType, FormModalInstance } from '../type';

const FormModalContext = createContext<ContextType<AnyObject>>({
	store: { open: false, title: '', initData: null },
	open: () => {},
	close: () => {},
	__INTERNAL__: () => {}
});

class FormModalStore<T> {
	private store: { open: boolean; title: string; initData: T };
	private update_store: AnyObject = {};

	constructor() {
		this.store = { open: false, title: '', initData: null };
	}

	// 组件实例内部方法
	__INTERNAL__ = (updateFn: Dispatch<SetStateAction<{}>>) => {
		this.update_store.update = updateFn;
	};

	getDetail: () => FormModalInstance<T> = () => ({
		store: this.store,
		open: this.setModalOpen,
		close: this.setModalClose,
		__INTERNAL__: this.__INTERNAL__
	});

	setModalOpen = (data: { title: string; initData: T }) => {
		const { title = '', initData } = data || {};
		this.store.open = true;
		this.store.title = title;
		this.store.initData = initData;
		this.update_store.update?.();
	};

	setModalClose = () => {
		this.store.open = false;
		this.update_store.update?.();
		this.store.title = '';
	};
}

export { FormModalContext, FormModalStore };
